//
//  MeditationsTimerViewController.m
//  Myrna-Mindfulness
//
//  Created by Anders J.R. Petersen on 04/09/13.
//  Copyright (c) 2013 Anders J.R. Petersen. All rights reserved.
//

#import "MeditationsTimerViewController.h"

@interface MeditationsTimerViewController (){
     AVAudioPlayer *avPlayer;
}

@property float time;
@property Boolean running;

@end

@implementation MeditationsTimerViewController

@synthesize time;
@synthesize running;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    time = 0;
    
    [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(updateProgressView) userInfo:nil repeats:YES];
    
    
    [self.slideBar setValue:0.0];
    
    [self setupIntervalLabel];    
    [self.intervalLabel setFont:[UIFont fontWithName:@"Didot-Bold" size:15.0]];
    self.intervalLabel.textAlignment = NSTextAlignmentRight;
    
    [self initializeBellSound];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
 }

-(void)updateProgressView{

    float progress = time/[self getIntervalSecValue];
    
      //  NSLog(@"time: %f og progress %f og delta %f", time, progress, [self getIntervalSecValue]);
    
    
    if(running){
        time = time + .1;
     
        if(progress >= 1){
            [avPlayer play];
            running = NO;
        }
    }
    
    self.progressBar.progress = progress;
    
    
}
 
- (IBAction)playButtonClicked:(id)sender {
    running = YES;
    [avPlayer stop];
    [avPlayer setCurrentTime:0];
}

- (IBAction)pauseButtonClicked:(id)sender {
    running = NO;
}

- (IBAction)revButtonClicked:(id)sender {
    running = NO;
    time = 0;
    [avPlayer stop];
    [avPlayer setCurrentTime:0];
}

- (IBAction)sliderBarChanged:(id)sender {
    [self setupIntervalLabel];
}

-(void)setupIntervalLabel{
    self.intervalLabel.text = [[NSString alloc] initWithFormat:@"%d minutter",[self getIntervalMinuteValue]];
}

-(int)getIntervalMinuteValue{
    return (int)(self.slideBar.value*60);
}

-(float)getIntervalSecValue{
    return (float)([self getIntervalMinuteValue]*60);
}

-(void)initializeBellSound{
    NSString *stringPath =[[NSBundle mainBundle]pathForResource:@"goong" ofType:@"caf"];
    NSURL *url = [NSURL fileURLWithPath:stringPath];
    
    NSError *error;
    
    avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
}

@end
